package io.renren.modules.reception.controller;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.NoRepeatSubmit;
import io.renren.common.utils.FastIDUtil;
import io.renren.modules.member.entity.TStoreMemberConsumeRecordEntity;
import io.renren.modules.member.service.TStoreMemberAccountDetailService;
import io.renren.modules.member.service.TStoreMemberConsumeRecordService;
import io.renren.modules.member.service.TStoreMemberRuleService;
import io.renren.modules.reception.entity.vo.FastfoodInfo;
import io.renren.modules.reception.entity.vo.FoodVo;
import io.renren.modules.reception.entity.vo.PayVo;
import io.renren.modules.store.entity.TStoreAccountListEntity;
import io.renren.modules.store.entity.TStoreBrandEntity;
import io.renren.modules.store.service.TStoreAccountListService;
import io.renren.modules.store.service.TStoreAccountUnitService;
import io.renren.modules.store.service.TStoreBrandService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.reception.entity.TStoreFastfoodRecordEntity;
import io.renren.modules.reception.service.TStoreFastfoodRecordService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-02-20 21:20:04
 */
@RestController
@RequestMapping("reception/tstorefastfoodrecord")
public class TStoreFastfoodRecordController extends AbstractController {
    @Autowired
    private TStoreFastfoodRecordService tStoreFastfoodRecordService;
    @Autowired
    private TStoreBrandService storeBrandService;
    @Autowired
    private TStoreMemberAccountDetailService storeMemberAccountDetailService;
    @Autowired
    private TStoreAccountUnitService accountUnitService;
    @Autowired
    private TStoreMemberRuleService memberRuleService;
    @Autowired
    private TStoreMemberConsumeRecordService consumeRecordService;
    @Autowired
    private TStoreAccountListService storeAccountListService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("sellerId", getSeller());
        PageUtils page = tStoreFastfoodRecordService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 快餐列表
     */
    @RequestMapping("/listFastFood")
    public R listFastFood(@RequestParam Map<String, Object> params) {
        params.put("sellerId", getSeller());
//        if (!params.get("key").equals("")) {
//            TStoreBrandEntity brandEntity = storeBrandService.getOne(new QueryWrapper<TStoreBrandEntity>()
//                    .eq("brand_no", params.get("key"))
//            );
//            params.put("key", brandEntity.getBrandId());
//        }
        Page<TStoreFastfoodRecordEntity> page = tStoreFastfoodRecordService.listFastFood(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{takeoutId}")
    @RequiresPermissions("reception:tstorefastfoodrecord:info")
    public R info(@PathVariable("takeoutId") Long takeoutId) {
        TStoreFastfoodRecordEntity tStoreFastfoodRecord = tStoreFastfoodRecordService.getById(takeoutId);

        return R.ok().put("tStoreFastfoodRecord", tStoreFastfoodRecord);
    }

    /**
     * 保存
     */
    @NoRepeatSubmit
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody FastfoodInfo fastfoodInfo) {
        fastfoodInfo.getFastfoodInfo().setTime(new Date());
        //保存账单（未付款）
        if (fastfoodInfo.getFastfoodInfo().getPaySign() == 1){
            fastfoodInfo.getFastfoodInfo().setSellerId(getSeller());
            fastfoodInfo.getFastfoodInfo().setFastfoodId(FastIDUtil.fastId());
            fastfoodInfo.getFastfoodInfo().setStatus(1);
        }
        //结账
        else {
            //直接结账（保存账单后的结账则不用）
            if (fastfoodInfo.getFastfoodInfo().getDirectPayFlag()){
                fastfoodInfo.getFastfoodInfo().setSellerId(getSeller());
                fastfoodInfo.getFastfoodInfo().setFastfoodId(FastIDUtil.fastId());
            }
            fastfoodInfo.getFastfoodInfo().setStatus(2);
        }
        if (fastfoodInfo.getFastfoodInfo().getFoodVos().size() == 0) {
            fastfoodInfo.getFastfoodInfo().setFoodVo(fastfoodInfo.getFastfoodInfo().getFoodVo());
        } else {
            Object json = JSONObject.toJSON(fastfoodInfo.getFastfoodInfo().getFoodVos());
            fastfoodInfo.getFastfoodInfo().setFoodVo(json.toString());
        }
        tStoreFastfoodRecordService.saveOrUpdate(fastfoodInfo.getFastfoodInfo());

        //挂账单位
        if (fastfoodInfo.getFastfoodInfo().getAccountId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("accountId",fastfoodInfo.getFastfoodInfo().getAccountId());
            map.put("sellerId",getSeller());
            map.put("money",fastfoodInfo.getFastfoodInfo().getTotalMoney());
            accountUnitService.updateAccount(map);

            TStoreAccountListEntity storeAccountListEntity = new TStoreAccountListEntity();
            storeAccountListEntity.setAccountId(fastfoodInfo.getFastfoodInfo().getAccountId())
                    .setOrderId(fastfoodInfo.getFastfoodInfo().getFastfoodId())
                    .setMoney(fastfoodInfo.getFastfoodInfo().getTotalMoney())
                    .setCreateTime(new Date())
                    .setCreateUser(getUser().getUsername())
                    .setFoodVo(JSONObject.toJSON(fastfoodInfo.getFastfoodInfo().getFoodVos()).toString())
                    .setStatus(1)
                    .setType(1);
            storeAccountListService.save(storeAccountListEntity);
        }

        if (fastfoodInfo.getFastfoodInfo().getMemberId() != null){
            //更新会员账户会员
            double exchangeIntegral = memberRuleService.ExchangeIntegral(getSeller(), fastfoodInfo.getFastfoodInfo().getMemberTypeId());
            Map<String, Object> map = new HashMap<>();
            TStoreMemberConsumeRecordEntity consumeRecordEntity = new TStoreMemberConsumeRecordEntity();
            List<PayVo> list = fastfoodInfo.getFastfoodInfo().getPayVo();
            for (int i = 0 ; i < list.size() ;i++){
                if (list.get(i).getPayMethodName().equals("储值卡")){
                    double memberIntegral = Math.ceil(list.get(i).getPayMoney()*exchangeIntegral);
                    map.put("integral",memberIntegral);
                    map.put("amount",list.get(i).getPayMoney());
                    consumeRecordEntity.setConsumeAmout(list.get(i).getPayMoney());
                    map.put("memberId",fastfoodInfo.getFastfoodInfo().getMemberId());
                    storeMemberAccountDetailService.updateMemberAccountConsume(map);

                    //插入会员消费记录表
                    consumeRecordEntity.setCreateTime(new Date());
                    consumeRecordEntity.setCreateUserId(getUserId());
                    consumeRecordEntity.setMemberId(fastfoodInfo.getFastfoodInfo().getMemberId());
                    consumeRecordEntity.setOrderId(Long.parseLong(fastfoodInfo.getFastfoodInfo().getFastfoodId()));
                    consumeRecordEntity.setRemark(fastfoodInfo.getFastfoodInfo().getRemark());
                    consumeRecordEntity.setSellerId(getSeller());
                    consumeRecordEntity.setDiscount(fastfoodInfo.getFastfoodInfo().getDiscount());
                    consumeRecordService.save(consumeRecordEntity);
                }
            }
        }

        TStoreFastfoodRecordEntity foodInfo = tStoreFastfoodRecordService.getOne(new QueryWrapper<TStoreFastfoodRecordEntity>()
                .eq("fastfood_id", fastfoodInfo.getFastfoodInfo().getFastfoodId())
        );

        TStoreBrandEntity brandInfo = storeBrandService.getOne(new QueryWrapper<TStoreBrandEntity>()
                .eq("brand_id", foodInfo.getBrand())
        );

        foodInfo.setBrandNo(brandInfo.getBrandNo());
        foodInfo.setBrandName(brandInfo.getBrandName());

        TStoreBrandEntity storeBrandEntity = new TStoreBrandEntity();
        if (fastfoodInfo.getFastfoodInfo().getReallyGet() == 0) {
            //挂单也要释放餐牌
            if (fastfoodInfo.getFastfoodInfo().getAccountId() != null){
                storeBrandEntity.setStatus(1);
            }
            //免单也要释放
            if (fastfoodInfo.getFastfoodInfo().getPayMethodName().equals("免单")){
                storeBrandEntity.setStatus(1);
            }else {
                storeBrandEntity.setStatus(2);
            }
        } else {
            storeBrandEntity.setStatus(1);
        }

        storeBrandEntity.setBrandId(fastfoodInfo.getFastfoodInfo().getBrand());
        storeBrandService.updateById(storeBrandEntity);
        return R.ok().put("foodInfo", foodInfo);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("reception:tstorefastfoodrecord:update")
    public R update(@RequestBody TStoreFastfoodRecordEntity tStoreFastfoodRecord) {
        tStoreFastfoodRecordService.updateById(tStoreFastfoodRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("reception:tstorefastfoodrecord:delete")
    public R delete(@RequestBody Long[] takeoutIds) {
        tStoreFastfoodRecordService.removeByIds(Arrays.asList(takeoutIds));

        return R.ok();
    }

}
